// goodsTrade.js
const app = getApp()
import { requestApi } from '../../../api'
import { formatImage } from '../../../utils/formatImage'
import { formatPrice } from '../../../utils/util'
import { dateFormat } from '../../../utils/dateFormat'
import { logUpload } from '../../../utils/logUpload'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        loading: false,
        checkItem: [{
            value: true,
            checked: true,
        }],
        loadingText: '',
        gid: '',
        channel: '',
        goodsData: [],
        winWidth: '',
        winHeight: '',
        skuSpec: '',
        skuPrice: '',
        skuId: '',
        skuImage: '',
        amount: '0',
        comment: '',
        sellerUid: '',
        buyerUid: '',
        couponId: '',
        payPrice: '',
        remainTip: 0,
        activityType: '',          // 活动类型   1:折扣商品；2：大拼团 3:亲密购(按亲密购价格购买)  '':普通商品(原价购买)
        activityId: '',            // 亲密购id
        entrenceTime: '',
        placeholderFlag: false,    // 当出现弹窗时，隐藏留言备注中的内容
        selectIndex: 0,    // 用户选中地址下标
        needEditAddressFlag: false, // 根据商家要求：该商品的收货地址是否需要验证身份证号和照片，不合格的地址需要重新编辑
        identifyType: '0',
        addressData: null,
        addressIndex: 0,
        bid_seller_uid: '',
        max_available_coupon: null, //商品最优优惠券信息
        isRequireOrder: false,
        wechat_live_trace_id: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const self = this;
        let gid = options.gid
        let channel = options.channel || 'wx_xcx'

        self.defaultLoadingText = '加载中...'
        self.orderStatus = false
        self.payStatus = false
        self.tradeNo = ''

        // 获取当前登陆的uid
        wx.getStorage({
            key: 'userinfo',
            success: (res) => {
                self.data.buyerUid = res.data.uid
            }
        })

        // 清除上次选中地址信息
        wx.removeStorage({
            key: 'selectIndex',
        })

        let systemInfo = {}

        try {
            systemInfo = wx.getSystemInfoSync()
        } catch (e) {
            // Do something when catch error
        }

        // 显示loading
        self.setData({
            winWidth: systemInfo.windowWidth,
            winHeight: systemInfo.windowHeight,
            gid: gid,
            skuSpec: decodeURIComponent(options.sku_spec),
            skuPrice: options.sku_price,
            skuId: options.sku_id,
            skuImage: decodeURIComponent(options.sku_img),
            channel: channel,
            activityType: options.activity_type || '',
            activityId: options.activity_id || '',
            bid_seller_uid: options.bid_seller_uid || '',
            entrenceTime: dateFormat('yyyy-MM-dd hh:mm:ss:S'),
        })

        const eventChannel = self.getOpenerEventChannel()
        // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
        eventChannel.on('max_available_coupon', function (max_available_coupon) {
            const price = parseInt(options.sku_price.replace(/,/g, ''), 10)

            self.setData({
                skuPrice: formatPrice((max_available_coupon.amount * 1 + price * 100) / 100),
                coupon_seller_amount: formatPrice(max_available_coupon.coupon_seller_amount / 100),
                coupon_platform_amount: formatPrice(max_available_coupon.coupon_platform_amount / 100),
                seller_coupon_no: max_available_coupon.seller_coupon_no,
                seller_coupon_id: max_available_coupon.seller_coupon_id,
                platform_coupon_id: max_available_coupon.platform_coupon_id,
                platform_coupon_no: max_available_coupon.platform_coupon_no,
                amount: formatPrice(max_available_coupon.amount / 100),
                max_available_coupon
            })
        })

        // this.getOrderData(gid, channel)
    },

    onReady() {
        this.dialog = this.selectComponent("#authorizeDialog");
    },

    onShow: function () {
        var self = this;

        if (!app.toLogin()) {
            this.setData({
                loading: true
            })

            return false
        }

        // 若登陆后页面参数缺失，跳转至商品详情页
        if (this.data.skuId == '') {
            wx.redirectTo({
                url: '/pages/index/index?channel=wx_xcx',
            })
        }
        // wx.checkBeforeAddOrder({
        //     success(res) {
        //         if(res.data.requireOrder == 1) {
        //             self.setData({
        //                 isRequireOrder: res.data.requireOrder ? true : false,
        //                 wechat_live_trace_id: res.data.traceId ? res.data.traceId : ''
        //             })
        //         }
        //     },
        //     fail(res) {
        //         console.log(res);
        //     }
        // })
        this.getOrderData(this.data.gid, this.data.channel)
    },

    // 阅读购买须知选中
    purchaseNotesCheck: function (e) {
        let checked = e.detail.value[0] ? true : false

        this.setData({
            checkItem: [{
                value: true,
                checked: checked,
            }]
        })
    },

    // 跳转协议页面
    readPurchaseNotes: function (e) {
        let protocolName = e.currentTarget.dataset.protocol
        let url = `../purchaseNotes/purchaseNotes?protocol_name=${protocolName}`

        wx.navigateTo({
            url: url,
        })
    },

    _cancelEvent() {
        this.setData({
            placeholderFlag: false
        })
        this.dialog.hideDialog();
    },

    _confirmEvent() {
        this.setData({
            checkItem: [{
                value: true,
                checked: true,
            }]
        })

        this.payOrder()
        this.dialog.hideDialog();
    },

    // 恢复loading初始状态
    resetLoadingSettings: function () {
        this.setData({
            loading: true,
        })
        this.data.loadingText = this.defaultLoadingText
    },

    toCoupon: function () {
        // let url = '/pages/personal/coupon/coupon?flag=true&seller_uid=' + this.data.sellerUid + '&gid=' + this.data.gid + '&sku_id=' + this.data.skuId + '&channel=' + this.data.channel

        // wx.navigateTo({
        //   url: url,
        // })
    },

    // 跳转到地址列表页
    toAddress: function () {
        const url = '/pages/personal/addressList/addressList?isSelect=select' + '&channel=' + this.data.channel
            + '&refer=order&identifyType=' + this.data.identifyType

        wx.navigateTo({
            url,
        })
    },

    // TODO 需要重构
    // 跳转到地址详情页
    goToAddressDetail() {
        const url = '../../personal/addressDetail/addressDetail?index=' + this.data.addressIndex + '&channel=' + this.data.channel
            + '&refer=order&identifyType=' + this.data.identifyType

        wx.navigateTo({
            url,
        })
    },

    getComment: function (e) {
        this.setData({
            comment: e.detail.value
        })
    },

    payOrder: function (e) {
        let channel = this.data.channel
        let selectIndex = this.data.selectIndex

        wx.getStorage({
            key: 'selectIndex',
            success: function (res) {
                selectIndex = res.data
            },
        })

        // 无收货地址/地址需要补充身份证号或者照片
        // if (!this.data.addressData || this.data.needEditAddressFlag) {
        //     wx.showModal({
        //         title: '提示',
        //         showCancel: false,
        //         content: !this.data.addressData ? '请添加收货地址' : '请在地址中补充清关身份信息',
        //     })

        //     return false
        // }

        // 没有勾选购买须知
        if (!this.data.checkItem[0].checked) {
            this.dialog.showDialog()
            this.setData({
                placeholderFlag: true
            })

            return false
        } else {
            this.setData({
                placeholderFlag: false
            })
        }

        let param = {
            seller_uid: this.data.sellerUid,
            buyer_uid: this.data.buyerUid,
            gid: this.data.gid,
            buyer_comment: this.data.comment,
            sku_id: this.data.skuId,
            coupon_no: this.data.platform_coupon_no,
            // coupon_id: this.data.platform_coupon_no,
            // seller_coupon_id: this.data.seller_coupon_no,
            seller_coupon_no: this.data.seller_coupon_no,
            booking_source: 10,
            address_id: this.data.addressData.id,
        }

        let activityType = this.data.activityType
        let uploadParam = {
            order_pay_result_type: null,
            order_pay_channel: 3,
            trade_no: null,
            log_type: 1,
            ref_page_id: 'OFPopGoodsSKUViewController',
            cur_page_id: 'OFOrderEditViewController',
        }

        if (activityType) {
            if (activityType == 2) {
                param.is_group_goods = 1
            }
            param.activity_type = activityType
        }

        if (this.data.activityId) {
            param.activity_id = this.data.activityId
        }

        if (this.data.goodsData.goodsgoods_channel_source == 3) {
            param.channel = 0
        } else {
            param.channel = 8
        }

        // 防止在同一个页面内多次下单
        if (this.payStatus) { // 已支付成功
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: '您已付款成功，请到订单详情页查看',
            })

            return false
        }

        if (this.orderStatus) { // 已下单
            // 进行付款操作，付款成功后跳转至订单详情页
            let tradeDetailUrl = '../../trade/tradeDetail/tradeDetail?trade_no=' + this.tradeNo + '&channel=' + this.data.channel

            this.weixinPay(this.tradeNo, () => {
                this.navigateTo(tradeDetailUrl)
            })

            return false
        }

        this.setData({
            loading: false,
            loadingText: '正在下单中...'
        })

        this.orderStatus = true;
        // 如商品是报价，则会返回bid_seller_uid，支付的时候，替换现有的seller_uid
        if (Number(this.data.bid_seller_uid) > 0) {
            param['seller_uid'] = this.data.bid_seller_uid;
        }

        if (this.data.isRequireOrder) {
            param['wechat_live_trace_id'] = this.data.wechat_live_trace_id;
        }
        console.log(param)
        app.request({
            url: requestApi.payUrl,
            method: 'POST',
            data: param,
        }, (data) => {
            let tradeNo = data.original.trade_no
            let tradeDetailUrl = '../../trade/tradeDetail/tradeDetail?trade_no=' + tradeNo + '&channel=' + this.data.channel;

            this.tradeNo = tradeNo
            uploadParam.trade_no = tradeNo
            uploadParam.order_pay_result_type = 1

            // 代购商品，直接跳转到订单详情页
            if (data.original.trade_status == 1) {
                this.navigateTo(tradeDetailUrl)

                return false
            } else {
                this.setData({
                    paySign: data.original.wechat_pay_detail
                })
            }

            // 进行付款操作，付款成功后跳转至订单详情页
            this.weixinPay(tradeNo, () => {
                this.navigateTo(tradeDetailUrl)
            })
        }, (error) => {
            this.orderStatus = false
            uploadParam.order_pay_result_type = 2
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
            this.resetLoadingSettings()
        })

        uploadParam.cur_page_entrance_time = this.data.entrenceTime

        logUpload.handleUpload(uploadParam)
    },

    navigateTo(url) {
        wx.redirectTo({
            url: url
        })
    },

    getOrderData(gid, channel) {
        // 可以由personal/addressList/addressList或者addressDetail两个页面跳转到该“下单确认页”，传递了地址信息 addressData
        const addressPromise = this.data.addressData && this.data.addressData.id ? this.data.addressData.id : new Promise((resolve, reject) => {
            // 获取收货地址信息
            app.request({
                url: requestApi.confirmAddressUrl,
            }, data => {
                let addressData = ''

                if (data.original.status == 'success') {
                    if (data.original.address_list && data.original.address_list.length) {
                        addressData = data.original.address_list[0]

                        // 存储storage
                        wx.setStorage({
                            key: 'addressList',
                            data: data.original.address_list || [],
                        })
                    }

                    if (addressData.id_number) {
                        addressData.id_number_cn = addressData.id_number.substr(0, 4) + '********' + addressData.id_number.substr(-6, 6)
                    }

                    this.setData({
                        addressData: addressData,
                    })

                    resolve(addressData ? addressData.id : addressData)
                }
            }, (error) => {
                wx.showModal({
                    title: '提示',
                    showCancel: false,
                    content: error,
                })

                reject(error)
            })
        })

        // 可以由personal/addressList/addressList或者addressDetail两个页面跳转到该“下单确认页”，传递了身份证校验信息 addressData.identifyType
        const goodsPromise = this.data.addressData && this.data.addressData.identifyType ? this.data.addressData.identifyType : new Promise((resolve, reject) => {
            // 获取商品信息
            app.request({
                url: requestApi.goodsDetailUrl,
                data: {
                    gid: gid,
                    intimate_purchase_id: this.data.activityId,
                    channel: channel
                },
            }, data => {
                let goodsData, payPrice
                let skuPrice = parseInt(this.data.skuPrice.replace(/,/g, ''), 10)

                if (data.original.status == 'success') {
                    if (data.original.data.user_list_for_confirm_order && data.original.data.user_list_for_confirm_order && data.original.data.user_list_for_confirm_order.length) {
                        data.original.data.user_list_for_confirm_order.forEach(function (item) {
                            if (item.path && item.path.length) {
                                item.new_path = formatImage.cdnImage(item.path, formatImage.THUMBNAIL_XS)
                            }
                        })
                    }

                    let remainTip = 0
                    let remainTime = data.original.data.remain_time_for_confirm_order

                    if (data.original.data.remain_time_for_confirm_order) {
                        let interval = setInterval(() => {
                            remainTip = this.getRemainTime(remainTime)
                            remainTime = remainTime - 1
                            this.setData({
                                remainTip: remainTip,
                            })

                            if (remainTime < 0) {
                                clearInterval(interval)
                            }
                        }, 1000)
                    }

                    goodsData = this.formatData(data.original.data)

                    if (goodsData.is_show_customs == 1 && (goodsData.goods_shipping_info.delivery_mode == 2)) {
                        payPrice += parseInt(String(goodsData.goods_shipping_info.new_customs_duties).replace(/,/g, ''), 10)
                    }

                    payPrice = formatPrice(skuPrice + goodsData.goods_shipping_info.new_shipping_rate)

                    let amount = this.data.amount
                    let amountStr = ''

                    if (amount.indexOf(',') !== -1) {
                        let amountArr = amount.split(',')

                        for (let i = 0; i < amountArr.length; i++) {
                            amountStr += amountArr[i]
                        }
                    } else {
                        amountStr = amount
                    }

                    // TODO 计算“价格”的逻辑有问题，要区分“数值型”和“格式化后”的价格
                    // 多个页面涉及价格的逻辑很混乱
                    let priceStr = payPrice

                    if (payPrice.indexOf(',') !== -1) {
                        priceStr = ''

                        let payPriceArr = payPrice.split(',')

                        for (let i = 0; i < payPriceArr.length; i++) {
                            priceStr += payPriceArr[i]
                        }
                    }

                    this.resetLoadingSettings()

                    this.setData({
                        goodsData,
                        payPrice: formatPrice(priceStr - amountStr),
                        sellerUid: goodsData.seller_info.seller_uid,
                        loading: true,
                    })

                    // customs_identify_requires 商品是否需要补充身份信息 0:不需要 1:号码&照片 2:仅号码
                    const identifyType = goodsData.goods_shipping_info.customs_identify_requires

                    this.data.identifyType = identifyType
                    resolve(identifyType)
                }
            }, error => {
                wx.showModal({
                    title: '提示',
                    showCancel: false,
                    content: error,
                })

                reject(error)
            })
        })

        Promise.all([addressPromise, goodsPromise])
            .then(result => {
                const addressId = result[0]
                const identifyType = result[1]

                // 商品是否需要补充身份信息 0:不需要 1:号码&照片 2:仅号码
                if (parseInt(identifyType, 10) === 0 || this.data.addressData && this.data.addressData.identifyType) {
                    this.setData({
                        needEditAddressFlag: false,
                    })

                    return false
                }

                if (addressId === '') return false

                this.checkIdentityInformation(addressId, this.data.gid, (data) => {
                    this.setData({
                        needEditAddressFlag: parseInt(data.is_need_supplement, 10) === 1,
                    })
                })
            })
            .catch(error => {
                console.log('error', error)
            })
    },

    // 确认订单页面是否需要补充身份信息
    checkIdentityInformation(addressId, gid, callback) {
        const params = {
            gid,
            address_id: parseInt(addressId, 10),
        }

        // 确认订单页面是否需要补充身份信息
        app.request({
            url: requestApi.checkIdentityInformation,
            data: params,
        }, data => {
            if (data.original.status === 'success') {
                callback && callback(data.original.data)
            }
        }, error => {
            console.log(error)
        })
    },

    weixinPay(tradeNo, successCallback) { // TODO 确认订单页、订单详情页，这两个页面的支付逻辑统一处理
        this.setData({
            loading: false,
            loadingText: '正在支付中...'
        })

        this.payStatus = true;

        if (this.data.isRequireOrder) {
            this.getRequireOrder(tradeNo, successCallback);
        } else {
            this.paymentHandler(tradeNo, 'requestPayment', successCallback);
        }

        this.payStatus = false
        this.resetLoadingSettings()
    },

    // 处理请求返回的数据
    formatData: function (data) {
        if (data.product_cover_image && data.product_cover_image.path) {
            data.product_cover_image.new_path = formatImage.cdnImage(data.product_cover_image.path, formatImage.THUMBNAIL_S)
        }

        if (data.seller_info && data.seller_info.avatarimage) {
            data.seller_info.avatarimage = formatImage.cdnImage(data.seller_info.avatarimage, formatImage.THUMBNAIL_S)
        }

        if (data.global_icon && data.global_icon.path) {
            data.global_icon.path_cn = formatImage.cdnImage(data.global_icon.path, formatImage.THUMBNAIL_M)
        }

        data.goods_shipping_info.new_shipping_rate = data.goods_shipping_info.shipping_rate ? (data.goods_shipping_info.shipping_rate / 100) : 0

        data.goods_sku.forEach(item => {
            if (item.sku_id == this.data.skuId) {
                data.goods_shipping_info.new_customs_duties = item.customs_duties ? item.customs_duties / 100 : 0
            }
        })

        return data
    },

    // 倒计时功能
    getRemainTime: function (time) {
        if (time < 0) return false

        let differTimestamp = time
        let deltaHour = Math.floor(differTimestamp / (60 * 60))
        let deltaMinute = Math.floor((differTimestamp % (60 * 60)) / 60)
        let deltaSecond = Math.floor(differTimestamp % 60)
        deltaHour = deltaHour < 10 ? ('0' + deltaHour) : deltaHour
        deltaMinute = deltaMinute < 10 ? ('0' + deltaMinute) : deltaMinute
        deltaSecond = deltaSecond < 10 ? ('0' + deltaSecond) : deltaSecond
        let deltaDate = deltaHour + ':' + deltaMinute + ':' + deltaSecond

        return deltaDate
    },

    // 获取视频号订单信息
    getRequireOrder(trade_no, successCallback) {
        const { channel  } = this.data;
        const self = this;
        
        wx.showLoading({
            title: '数据请求中',
        });
        app.request({
            url: requestApi.wxLivePayUrl,
            method: 'POST',
            data: {
                trade_no,
                is_new_ver: true,
                channel: channel
            },
        }, (data) => {
            self.setData({
                paySign: data.original.wechat_pay_detail
            })
            self.paymentHandler(trade_no, 'requestOrderPayment', successCallback);
        }, (error) => {
            // 
        }, () => {
            wx.hideLoading();
        })
    },

    paymentHandler(trade_no, paymentType, successCallback) {
        let signData = this.data.paySign || {};

        delete signData['status']
        delete signData['appId']

        // 微信支付成功回调
        signData.success = () => {
            // 回调通知接口
            app.request({
                // url: WEIXIN_PAY_FRONT_CALLBACK,
                url: requestApi.weixinPayCallback,
                method: 'POST',
                data: {
                    trade_no
                }
            }, (data) => {
                // successCallback && successCallback()
            }, (error) => {
                // wx.showModal({
                //   title: '提示',
                //   showCancel: false,
                //   content: error,
                // })
            }, () => {
                successCallback && successCallback()
            })
        }

        // 微信支付失败回调
        signData.fail = (error) => {
            if (error.errMsg == paymentType + ':fail cancel') { // 用户取消支付
            } else { // 调用支付失败 TODO 上报支付失败原因
                wx.showModal({
                    title: '提示',
                    showCancel: false,
                    content: error.errMsg,
                })
            }
        }

        wx[paymentType](signData);
        
    }
})